package ist.utl.pt.smartfleet.stationterminal;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

/*TODO ligar a BD
 * acabar de populate os campos que faltam
 * lançar o evento po server
 * 
 * */
public class CheckIn extends MapActivity {
	
	MapView mapView;
	private EditText name;
	private EditText address;
	private Address addr;
	private String addressInput;
	private double lat;
	private double lon;
	private long checkinTime;
	private Button searchButton;
	private Button okButton;
	private EditText nPassangers;
	private Geocoder gc;
    private boolean correctSearch;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.checkin);
		
		correctSearch = false;
		name = (EditText) findViewById(R.id.entry_nome);
		nPassangers = (EditText) findViewById(R.id.entry_nr_passangers);
		address = (EditText) findViewById(R.id.entry_morada);
		mapView = (MapView) findViewById(R.id.mapView2);
		searchButton = (Button)this.findViewById(R.id.pesquisar_morada);
		
		//gera o ID e mete na BD
    	/*mRowId = (savedInstanceState == null) ? null :
            (Long) savedInstanceState.getSerializable(BDAdapter.KEY_ROWID);
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras.getLong(BDAdapter.KEY_ROWID)
									: null;
		} */
		
		
		//LISTENER DO BOTAO DE PROCURA DE MORADA
		//faz as verificaçoes not null do campo da morada
		//da inicio a procura da morada
		searchButton = (Button)this.findViewById(R.id.pesquisar_morada);
		
		gc = new Geocoder(this); //create new geocoder instance
		
	    searchButton.setOnClickListener(new OnClickListener() {
	      public void onClick(View v) {
	    	  
	        addressInput = address.getText().toString(); //Get input text 
	        
	    	correctSearch = true;
        //    lat = 38.757106; //campo grande
         //   lon = -9.153544;
            
            navigateToLocation((lat * 1000000), (lon * 1000000), mapView);
					
	        try {
						
	          List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
						
	          if (foundAdresses.size() == 0) { //if no address found, display an error
	            Dialog locationError = new AlertDialog.Builder(CheckIn.this)
	              .setIcon(0)
	              .setTitle("Error")
	              .setPositiveButton(R.string.ok, null)
	              .setMessage("Sorry, your address doesn't exist.")
	              .create();
	            locationError.show(); 
	          }
	          else { //else display address on map
	         //   for (int i = 0; i < foundAdresses.size(); ++i) {
	              //Save results as Longitude and Latitude
	              //@todo: if more than one result, then show a select-list
	              addr = foundAdresses.get(0);
	              lat = addr.getLatitude();
	              lon = addr.getLongitude();
	           // }
	          navigateToLocation((lat * 1000000), (lon * 1000000), mapView);
	         // navigateToLocation((lat * 1000000), (lon * 1000000), mapView); //display the found address
	          }
	        }
	        catch (Exception e) {
	          //@todo: Show error message
	        } 
					
	      }
	    });
		

		//LISTENER DO BOTAO DE OK
		//faz as verificações not null do nome da morada e do nr de passageiros
		//passa os dados ao StationTerminal por bundle flag 1
		this.okButton = (Button)this.findViewById(R.id.ok);
		
		okButton.setOnClickListener(new OnClickListener() {
		      public void onClick(View v) {
		    	int nrPassengersInput = 0;
		        String nameInput = name.getText().toString(); //Get input text
		        String addredssInput = address.getText().toString();
		        
		        correctSearch = true;
		        
		        String size = nPassangers.getText().toString();
		        if ( size.compareTo("") != 0) 
		        	nrPassengersInput = Integer.parseInt(size);
		        else Toast.makeText(CheckIn.this, "Preencher todos os campos", Toast.LENGTH_SHORT).show();
		        
		        
		        if(nameInput.compareTo("") == 0 || nrPassengersInput > 4 || nrPassengersInput < 1  
		        		|| correctSearch == false || addredssInput .compareTo("") == 0 )
		        	Toast.makeText(CheckIn.this, "Preencher todos os campos", Toast.LENGTH_SHORT).show();
		        
		        else {
		        	Address x;
		        	
		        	   	
		        	
		        	
		        	lat = 38.757106; //campo grande
		            lon = -9.153544;
		            
		        	Bundle bundle = new Bundle();
	                bundle.putString("nome", nameInput);
	                bundle.putString("morada", addressInput);
	                bundle.putInt("nrPassageiros", nrPassengersInput);
	                bundle.putDouble("latitude", lat);
	                bundle.putDouble("longitude", lon);
	                
	                Intent mIntent = new Intent();
	                mIntent.putExtras(bundle);
	                mIntent.addFlags(1);
	                setResult(RESULT_OK, mIntent);
	                finish();
	                
		        }		
		      }
		    });

	
	} 
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	} 
	
	/**
	  * Navigates a given MapView to the specified Longitude and Latitude
	  */
	  public static void navigateToLocation (double latitude, double longitude, MapView mv) {
	    GeoPoint p = new GeoPoint((int) latitude, (int) longitude); //new GeoPoint
	    mv.displayZoomControls(true); //display Zoom (seems that it doesn't work yet)
	    MapController mc = mv.getController();
	    mc.animateTo(p); //move map to the given point
	    int zoomlevel = mv.getMaxZoomLevel(); //detect maximum zoom level
	    mc.setZoom(zoomlevel - 1); //zoom
	    mv.setSatellite(false); //display only "normal" mapview	
	  }

}
